package com.neborosoft.android.gui.adapters.listview;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
import com.neborosoft.FlyingDog.android.MyActivity;
import com.neborosoft.lib.collections.Containers;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: CM
 * Date: 27.12.12
 * Time: 14:38
 * To change this template use File | Settings | File Templates.
 */
public abstract class CursorToArrayAdapter extends CursorAdapter {
    private int resourceId;

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
        LayoutInflater inflater = LayoutInflater.from(context);
        return (TextView)inflater.inflate(resourceId, null);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        TextView textView = (TextView)view;
        String text = cursor.getString(0);
        textView.setText(text);
    }

    protected abstract List<String> getList();

    private Cursor createCursor(){
        List<String> list = getList();
        Cursor cursor = Containers.listToCursor(list);
        return cursor;
    }

    public CursorToArrayAdapter(Context context, int resourceId) {
        super(context, null, false/*autoQuery*/);
        this.resourceId = resourceId;
        notifyDataSetChanged();
    }

    boolean notifyDataSetChangedCalled = false;
    @Override
    public void notifyDataSetChanged() {
        if(notifyDataSetChangedCalled){//avoid recursion calling
            return;
        }
        notifyDataSetChangedCalled = true;
        Cursor cursor = createCursor();
        changeCursor(cursor);
        notifyDataSetChangedCalled = false;
    }
}
